package com.lincoln.framework.utils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * 中文转拼音处理
 * 
 * @author zwm
 * 
 * @version 2016-2-25 上午11:27:56
 */
public class PinYinUtils {

	public static String getPinYin(String string) {
		char[] cs = string.toCharArray();
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < cs.length; i++) {
			stringBuffer.append(getCharacterPinYin(cs[i]));
		}
		return stringBuffer.toString();
	}

	public static String getCharacterPinYin(char c) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
		try {
			String[] pinYin = PinyinHelper.toHanyuPinyinStringArray(c, format);
			if (pinYin != null) {
				return pinYin[0];
			}
		} catch (BadHanyuPinyinOutputFormatCombination ex) {
			ex.printStackTrace();
		}
		return String.valueOf(c);
	}

	/**
	 * 获取汉子的拼音首字母，英文单词保持不变
	 * 
	 * @param string
	 *            需要转换的汉子
	 * @return
	 */
	public static String getFirstPinYin(String string) {
		char[] cs = string.toCharArray();
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < cs.length; i++) {
			stringBuffer.append(getFirstCharacterPinYin(cs[i]));
		}
		return stringBuffer.toString();
	}

	public static char getFirstCharacterPinYin(char c) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_V);
		try {
			String[] pinYin = PinyinHelper.toHanyuPinyinStringArray(c, format);
			if (pinYin != null) {
				return pinYin[0].charAt(0);
			}
		} catch (BadHanyuPinyinOutputFormatCombination ex) {
			ex.printStackTrace();
		}
		return c;
	}
}
